#include "MP3Decoder.h"
#include <cstdio>
#include <unistd.h>

#include "sound.h"

int main(int argc, char *argv[])
{
    if(argc < 2)
    {
        printf("input a mp3 file path as a parameter\n");
        return 0;
    }

    snd_pcm_init();
    snd_pcm_set_period_size(1152);

    auto mp3Decoder = new MP3Decoder();

    bool ret = mp3Decoder->open(argv[1]);
    if (ret == false)
    {
        printf("mp3 decode failed\n");
        return 0;
    }

    uint8_t *pcmData = mp3Decoder->readDecodeFrame();

    printf("music total seconds: %d\n", mp3Decoder->getTotalSec());
    printf("music sample rate: %d\n", mp3Decoder->getRate());
    printf("music channels: %d\n", mp3Decoder->getChannels());
    printf("music frame size: %d\n", mp3Decoder->getFrameSize());

    while (1)
    {
        ret = snd_pcm_writei(snd_pcm_get(), pcmData, mp3Decoder->getFrameSize());
        if (ret < 0)
        {
            usleep(26000);
        }
        else
        {
            pcmData = mp3Decoder->readDecodeFrame();
            if (pcmData == nullptr)
            {
                printf("decode finish\n");
                break;
            }

            int time = mp3Decoder->getCurrrentSec();
            printf("decode time: %d\r", time);
            fflush(stdout);
        }
    }

    mp3Decoder->close();

    return 0;
}
